package com.commerce.product.controller;

import com.commerce.common.utils.Result;
import com.commerce.common.entity.FlashSale;
import com.commerce.common.entity.FlashSaleProduct;
import com.commerce.product.service.FlashSaleService;
import com.commerce.product.service.FlashSaleStockService;
import com.commerce.product.mapper.FlashSaleProductMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 秒杀公共接口控制器（前端展示）
 */
@Slf4j
@RestController
@RequestMapping("/api/flash-sale")
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
public class FlashSalePublicController {

    @Autowired
    private FlashSaleService flashSaleService;

    @Autowired
    private FlashSaleStockService flashSaleStockService;

    @Autowired
    private FlashSaleProductMapper flashSaleProductMapper;

    /**
     * 获取所有秒杀活动
     */
    @GetMapping("/list")
    public Result<List<FlashSale>> getAllFlashSales() {
        log.info("获取所有秒杀活动");
        List<FlashSale> flashSales = flashSaleService.getAllPeriods();
        return Result.success(flashSales);
    }

    /**
     * 获取正在进行的秒杀活动
     */
    @GetMapping("/active")
    public Result<FlashSale> getActiveFlashSales() {
        log.info("获取正在进行的秒杀活动");
        FlashSale activeFlashSale = flashSaleService.getCurrentFlashSale();
        return Result.success(activeFlashSale);
    }

    /**
     * 获取秒杀活动详情
     */
    @GetMapping("/{id}")
    public Result<FlashSale> getFlashSaleById(@PathVariable Long id) {
        log.info("获取秒杀活动详情，ID：{}", id);
        FlashSale flashSale = flashSaleService.getById(id);
        return Result.success(flashSale);
    }

    /**
     * 获取秒杀活动商品列表
     */
    @GetMapping("/products/{flashSaleId}")
    public Result<List<FlashSaleProduct>> getFlashSaleProducts(@PathVariable Long flashSaleId) {
        log.info("获取秒杀活动商品列表，活动ID：{}", flashSaleId);
        List<FlashSaleProduct> products = flashSaleService.getFlashSaleProducts(flashSaleId);
        return Result.success(products);
    }

    /**
     * 检查商品库存
     */
    @GetMapping("/stock/{flashSaleId}/{productId}")
    public Result<Integer> checkStock(@PathVariable Long flashSaleId, @PathVariable Long productId) {
        log.info("检查商品库存，活动ID：{}，商品ID：{}", flashSaleId, productId);
        try {
            Integer stock = flashSaleStockService.getRedisStock(flashSaleId, productId);
            return Result.success(stock);
        } catch (Exception e) {
            log.error("检查商品库存失败", e);
            return Result.error("检查库存失败");
        }
    }

    /**
     * 获取秒杀商品详情
     */
    @GetMapping("/product/{id}")
    public Result<FlashSaleProduct> getFlashSaleProductById(@PathVariable Long id) {
        log.info("获取秒杀商品详情，ID：{}", id);
        try {
            // 直接查询数据库获取秒杀商品详情
            FlashSaleProduct product = flashSaleProductMapper.selectById(id);
            return Result.success(product);
        } catch (Exception e) {
            log.error("获取秒杀商品详情失败", e);
            return Result.error("获取商品详情失败");
        }
    }

    /**
     * 获取商品秒杀状态
     */
    @GetMapping("/status/{flashSaleId}/{productId}")
    public Result<String> getProductStatus(@PathVariable Long flashSaleId, @PathVariable Long productId) {
        log.info("获取商品秒杀状态，活动ID：{}，商品ID：{}", flashSaleId, productId);

        try {
            // 检查活动是否存在且有效
            FlashSale flashSale = flashSaleService.getById(flashSaleId);
            if (flashSale == null) {
                return Result.success("ACTIVITY_NOT_FOUND");
            }

            // 检查活动状态
            if (flashSale.getStatus() != 1) {
                return Result.success("ACTIVITY_INACTIVE");
            }

            // 检查时间
            long currentTime = System.currentTimeMillis();
            long startTime = flashSale.getStartTime().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli();
            long endTime = flashSale.getEndTime().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli();

            if (currentTime < startTime) {
                return Result.success("NOT_STARTED");
            } else if (currentTime > endTime) {
                return Result.success("ENDED");
            }

            // 检查库存
            Integer stock = flashSaleStockService.getRedisStock(flashSaleId, productId);
            if (stock == null || stock <= 0) {
                return Result.success("SOLD_OUT");
            }

            return Result.success("AVAILABLE");

        } catch (Exception e) {
            log.error("获取商品秒杀状态失败", e);
            return Result.error("获取状态失败");
        }
    }

}
